跳至主要内容

OOP 物件導向程式設計

OOP是什麼?

全名「Object-oriented programming」 物件導向程式設計


我們為什麼需要物件導向呢?


想像一下你如果今天寫一個遊戲 你可能會寫一堆函數跟變數 玩家攻擊、玩家血量、敵人攻擊、敵人血量 等等等等...


如果此時把玩家與敵人包裝成物件 整體程式會比較好理解與規劃

玩家A = new Player(100, 10) // 100血、10攻
敵人B = new Enemy(30, 5) // 30血、5攻
玩家A.attack(敵人B)
敵人B.attack(玩家A)

OOP with C#

那接下來在C#裡實際介紹OOP 還記得之前的程式碼嗎?


OOP有幾項基礎知識


三大特性:

  1. 繼承(Inheritance)
  2. 封裝(Encapsulation)
  3. 多型(Polymorphism)
    • overload
    • override

實作


實戰

public abstract class Unit
{
public string Name { set; get; }
public int HP { set; get; }
protected int ATK;
public abstract void Attack(Unit unit);
}

interface IInfo
{
void ShowInfo();
}

public class Player : Unit
{
public Player(string Name, int HP = 100, int ATK = 10)
{
this.Name = Name;
this.HP = HP;
this.ATK = ATK;
}
public override void Attack(Unit unit)
{
unit.HP -= this.ATK;
Console.WriteLine($"玩家 {this.Name} 對敵人 {unit.Name} 造成 {this.ATK} 點傷害");
}

}

public class Enemy : Unit
{
public Enemy(string Name, int HP = 30, int ATK = 5)
{
this.Name = Name;
this.HP = HP;
this.ATK = ATK;
}
public override void Attack(Unit unit)
{
unit.HP -= this.ATK;
Console.WriteLine($"敵人 {this.Name} 對玩家 {unit.Name} 造成 {this.ATK} 點傷害");
}
}

請實作ShowInfo,讓輸出畫面呈現以下樣式

Player player = new Player("小明");
Enemy enemy = new Enemy("史萊姆");
player.ShowInfo();
enemy.ShowInfo();
player.Attack(enemy);
enemy.Attack(player);
Console.WriteLine("---- END ----");
player.ShowInfo();
enemy.ShowInfo();


課堂範例(?)

class Program
{
static void Main(string[] args)
{
player p = new player(100, 10);
player1 pp = new player1(1, 1);
p.attack();
pp.attack();
// new ABC();
Console.WriteLine("Hello, World!");
}
static void sayHi()
{
Console.WriteLine("HI");
}
static void sayHi(string name, int i, char c)
{
Console.WriteLine($"HI, {name}");
}
}

abstract class ABC{}

class player
{
protected int HP;
private int atk;
public player(int HP, int atk)
{
this.HP = HP;
this.atk = atk;
Console.WriteLine("123");
}
public void attack()
{
Console.WriteLine("攻擊!!!");
}
}

class player1 : player
{
public player1(int HP, int atk) : base(HP, atk)
{
}

public override void attack()
{
Console.WriteLine("攻擊2!!!");
}
}

學長示範interface(?)

namespace vscode_test;
class Program
{
static void Main(string[] args)
{
IRepository repo = new OracleRepository();
controller c = new controller(repo);
c.store();
}
}

class controller
{
IRepository repo;
public controller(IRepository repo)
{
this.repo = repo;
}
public void store()
{
this.repo.store();
}
}

interface IRepository
{
void store();
}

public class MySQLRepository : IRepository
{
public void store()
{
Console.WriteLine("Store somthing to mysql");
}
}

public class OracleRepository : IRepository
{
public void store()
{
Console.WriteLine("Store somthing to Oracle DB");
}
}

不喜歡C#? 參考學長的JS OOP


End